package com.zllkj.mm.util;

import android.app.Activity;
import android.content.ContentUris;
import android.content.Context;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Rect;
import android.net.Uri;
import android.os.Environment;
import android.provider.DocumentsContract;
import android.provider.MediaStore;
import android.widget.Toast;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;

/**
 * Created by Administrator on 2017/3/17.
 */

public class ImageUtils {
    /**
     * @param context
     * @param imageUri
     * @return
     */
    public static String getImageAbsolutePath(Activity context, Uri imageUri) {
        if (context == null || imageUri == null)
            return null;
        if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.KITKAT && DocumentsContract.isDocumentUri(context, imageUri)) {
            if (isExternalStorageDocument(imageUri)) {
                String docId = DocumentsContract.getDocumentId(imageUri);
                String[] split = docId.split(":");
                String type = split[0];
                if ("primary".equalsIgnoreCase(type)) {
                    return Environment.getExternalStorageDirectory() + "/" + split[1];
                }
            } else if (isDownloadsDocument(imageUri)) {
                String id = DocumentsContract.getDocumentId(imageUri);
                Uri contentUri = ContentUris.withAppendedId(Uri.parse("content://downloads/public_downloads"), Long.valueOf(id));
                return getDataColumn(context, contentUri, null, null);
            } else if (isMediaDocument(imageUri)) {
                String docId = DocumentsContract.getDocumentId(imageUri);
                String[] split = docId.split(":");
                String type = split[0];
                Uri contentUri = null;
                if ("image".equals(type)) {
                    contentUri = MediaStore.Images.Media.EXTERNAL_CONTENT_URI;
                } else if ("video".equals(type)) {
                    contentUri = MediaStore.Video.Media.EXTERNAL_CONTENT_URI;
                } else if ("audio".equals(type)) {
                    contentUri = MediaStore.Audio.Media.EXTERNAL_CONTENT_URI;
                }
                String selection = MediaStore.Images.Media._ID + "=?";
                String[] selectionArgs = new String[]{split[1]};
                return getDataColumn(context, contentUri, selection, selectionArgs);
            }
        } // MediaStore (and general)
        else if ("content".equalsIgnoreCase(imageUri.getScheme())) {
            // Return the remote address
            if (isGooglePhotosUri(imageUri))
                return imageUri.getLastPathSegment();
            return getDataColumn(context, imageUri, null, null);
        }
        // File
        else if ("file".equalsIgnoreCase(imageUri.getScheme())) {
            return imageUri.getPath();
        }
        return null;
    }


    public static String getDataColumn(Context context, Uri uri, String selection, String[] selectionArgs) {
        Cursor cursor = null;
        String column = MediaStore.Images.Media.DATA;
        String[] projection = {column};
        try {
            cursor = context.getContentResolver().query(uri, projection, selection, selectionArgs, null);
            if (cursor != null && cursor.moveToFirst()) {
                int index = cursor.getColumnIndexOrThrow(column);
                return cursor.getString(index);
            }
        } finally {
            if (cursor != null)
                cursor.close();
        }
        return null;
    }

    /**
     * @param uri The Uri to check.
     * @return Whether the Uri authority is ExternalStorageProvider.
     */
    public static boolean isExternalStorageDocument(Uri uri) {
        return "com.android.externalstorage.documents".equals(uri.getAuthority());
    }

    /**
     * @param uri The Uri to check.
     * @return Whether the Uri authority is DownloadsProvider.
     */
    public static boolean isDownloadsDocument(Uri uri) {
        return "com.android.providers.downloads.documents".equals(uri.getAuthority());
    }

    /**
     * @param uri The Uri to check.
     * @return Whether the Uri authority is MediaProvider.
     */
    public static boolean isMediaDocument(Uri uri) {
        return "com.android.providers.media.documents".equals(uri.getAuthority());
    }

    /**
     * @param uri The Uri to check.
     * @return Whether the Uri authority is Google Photos.
     */
    public static boolean isGooglePhotosUri(Uri uri) {
        return "com.google.android.apps.photos.content".equals(uri.getAuthority());
    }

    public static Bitmap getBitmap(String fileUrl, int destWidth, int destHeight) {
        BitmapFactory.Options options = new BitmapFactory.Options();
        options.inJustDecodeBounds = true;
        BitmapFactory.decodeFile(fileUrl, options);
        int outWidth = options.outWidth;
        int outHeight = options.outHeight;
        int sampleSize = 1;
        while (outHeight / sampleSize > destHeight || outWidth / sampleSize > destWidth) {
            sampleSize *= 2;
        }
        options.inJustDecodeBounds = false;
        options.inSampleSize = sampleSize;
        options.inPreferredConfig = Bitmap.Config.RGB_565;
        return BitmapFactory.decodeFile(fileUrl, options);
    }

    public static boolean writeBitmap(Context context, Bitmap bitmap, String dirPath, String fileName, Bitmap.CompressFormat format) {
        FileOutputStream fos = null;
        try {
            File file = null;
            File dirFile = createDir(dirPath);
            if (dirFile == null) {
                return false;
            }

            file = createFile(context, dirFile, fileName);
            if (file == null) {
                return false;
            }

            fos = new FileOutputStream(file, false);
            bitmap.compress(format, 100, fos);
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            Toast.makeText(context, "异常:" + e.getMessage(), Toast.LENGTH_SHORT).show();
            return false;
        } finally {
            if (fos != null) {
                try {
                    fos.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    /**
     * 在给定目录中创建目标文件
     *
     * @param fileName
     * @param dirFile
     * @return
     */
    public static File createFile(Context context, File dirFile, String fileName) {
        try {
            File file = new File(dirFile.getAbsolutePath() + File.separator + fileName);
            if (!file.exists() || file.isDirectory()) {
                boolean newFile = file.createNewFile();
                if (!newFile) {
                    return null;
                }
            }
            return file;
        } catch (Exception e) {
            e.printStackTrace();
            Toast.makeText(context, "创建目标文件失败！", Toast.LENGTH_SHORT).show();
            return null;
        }
    }

    /**
     * 根据给定的路径创建文件夹
     *
     * @param dirPath
     * @return
     */
    public static File createDir(String dirPath) {
        File dirFile = new File(dirPath);
        if (!dirFile.exists() || !dirFile.isDirectory()) {
            boolean success = dirFile.mkdirs();
            if (!success) {
                return null;
            }
        }

        return dirFile;
    }

    public static Bitmap createTextBitmap(String text, float textSize, int textColor, int bold) {

        Paint paint = new Paint(Paint.ANTI_ALIAS_FLAG);//创建画笔
        paint.setTextSize(textSize);//设置文字的大小
//        paint.setTypeface(Typeface.DEFAULT_BOLD);//文字的样式(加粗)
        paint.setStyle(Paint.Style.FILL_AND_STROKE);
        paint.setStrokeWidth(bold);
        paint.setColor(textColor);//文字的颜色

        Rect rect = new Rect();
        paint.getTextBounds(text, 0, text.length(), rect);

//        float textWidth = paint.measureText(text);
//        float textHeight = textWidth / text.length();
//        float height = TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_SP, textSize, context.getResources().getDisplayMetrics());
//        Bitmap bitmap = Bitmap.createBitmap((int) textWidth, (int) textHeight, Bitmap.Config.ARGB_8888);//创建一个宽度和高度都是400、32位ARGB图

        int width = rect.width();
        width = width > 0 ? width : 1;
        int height = rect.height();
        height = height > 0 ? height : 1;

        Bitmap bitmap = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888);//创建一个宽度和高度都是400、32位ARGB图

        Canvas canvas = new Canvas(bitmap);//初始化画布绘制的图像到icon上
        canvas.drawColor(Color.TRANSPARENT);//图层的背景色
        canvas.drawText(text, 0, rect.height() - 5, paint);//将文字写入。这里面的（120，130）代表着文字在图层上的初始位置
        canvas.save(/*canvas.ALL_SAVE_FLAG*/);//保存所有图层
        canvas.restore();

        return bitmap;
    }

//    public static Bitmap drawLogo(Context context, Bitmap bgBitmap, String text) {
//        Bitmap paper = BitmapFactory.decodeResource(context.getResources(), R.mipmap.rqcode1).copy(Bitmap.Config.RGB_565, true);
//        Paint paint = new Paint(Paint.ANTI_ALIAS_FLAG);
//        Canvas canvas = new Canvas(paper);
//        canvas.drawBitmap(bgBitmap, 82, 240, null);
////        int left = (bgBitmap.getWidth() - logo.getWidth()) / 2;
////        int height = ((int) (bgBitmap.getHeight() * 1.4) - logo.getHeight()) / 2;
//        paint.setAlpha(200);
//        paint.setTextSize(30);
//        paint.setColor(Color.RED);
////        canvas.drawBitmap(logo, left, height, paint);
//        canvas.drawText(text, 125, 220, paint);
//        canvas.save();
//
//        return paper;
//    }
//
//    public static Bitmap drawLogo_V(Context context, Bitmap bgBitmap, String text) {
//        Bitmap paper = BitmapFactory.decodeResource(context.getResources(), R.mipmap.rqcodev).copy(Bitmap.Config.RGB_565, true);
//        Paint paint = new Paint(Paint.ANTI_ALIAS_FLAG);
//        Canvas canvas = new Canvas(paper);
//        canvas.drawBitmap(bgBitmap, 160, 230, null);
////        int left = (bgBitmap.getWidth() - logo.getWidth()) / 2;
////        int height = ((int) (bgBitmap.getHeight() * 1.4) - logo.getHeight()) / 2;
//        paint.setAlpha(200);
//        paint.setTextSize(40);
//        paint.setColor(Color.RED);
////        canvas.drawBitmap(logo, left, height, paint);
//        canvas.drawText(text, 180, 250, paint);
//        canvas.save();
//
//        return paper;
//    }
//
//    public static Bitmap drawLogo_H(Context context, Bitmap bgBitmap, String text) {
//        Bitmap paper = BitmapFactory.decodeResource(context.getResources(), R.mipmap.rqcodeh).copy(Bitmap.Config.RGB_565, true);
//        Paint paint = new Paint(Paint.ANTI_ALIAS_FLAG);
//        Canvas canvas = new Canvas(paper);
//        canvas.drawBitmap(bgBitmap, 60, 210, null);
////        int left = (bgBitmap.getWidth() - logo.getWidth()) / 2;
////        int height = ((int) (bgBitmap.getHeight() * 1.4) - logo.getHeight()) / 2;
//        paint.setAlpha(200);
//        paint.setTextSize(40);
//        paint.setColor(Color.RED);
////        canvas.drawBitmap(logo, left, height, paint);
//        canvas.drawText(text, 80, 225, paint);
//        canvas.save();
//
//        return paper;
//    }

}
